package com.seaboxdata.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * HTTP请求工具类
 *
 * @Author zhaoliangtao
 * @Date 2018/10/31 14:30
 */
public class HttpUtil {

    /**
     * post提交
     *
     * @param url
     * @param data
     * @param appKey
     * @param appToken
     * @return String
     * @throws IOException
     */

    public static String doPost(String url, Map<String, Object> data, String appKey, String appToken) throws IOException {
        HttpURLConnection conn = null;
        OutputStreamWriter outer = null;
        try {
            URL restURL = new URL(url);
            conn = (HttpURLConnection) restURL.openConnection();
            conn.setConnectTimeout(1000 * 100);
            conn.setReadTimeout(1000 * 150);
            // form提交参数
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // POST请求方式
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);


            // 添加头部Header字段
            // 时间戳秒
            String timestamp = (System.currentTimeMillis() / 1000) + "";
            // 随机不重复字符串
            String nonce = Long.toHexString(System.currentTimeMillis()) + "-" + Long.toHexString((long) Math.floor(Math.random() * 0xFFFFFF));
            // 计算签名
            if (appToken != null) {
                String signature = SHA256Util.getSHA256StrJava(timestamp + appToken + nonce + timestamp).toUpperCase();
                conn.addRequestProperty("x-aep-signature", signature);
            }

            if (appKey != null) {
                conn.addRequestProperty("x-aep-appkey", appKey);
                conn.addRequestProperty("x-aep-timestamp", timestamp);
                conn.addRequestProperty("x-aep-nonce", nonce);
            }

            outer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 处理输入参数参数
            String params = handleParams(data);
            outer.write(params);
            outer.flush();

            // 获取返回结果
            InputStream is = conn.getInputStream();
            String result = inputStreamToString(is, "UTF-8");
            return result;
        } catch (IOException e) {
            throw e;
        } finally {
            if (outer != null) outer.close();
            if (conn != null) conn.disconnect();
        }
    }


    public static String doPost(String url, Map<String, Object> data) throws IOException {
        return doPost(url,data,null,null);
    }

    /**
     * 处理输入参数
     *
     * @param map
     * @return String
     */
    private static String handleParams(Map<String, Object> map) {
        StringBuffer sb = new StringBuffer();
        if (map != null) {
            for (Map.Entry<String, Object> e : map.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            return sb.substring(0, sb.length() - 1);
        } else {
            return "";
        }
    }

    /**
     * 处理输出结果
     *
     * @param is
     * @param charSet
     * @return
     * @throws IOException
     */
    private static String inputStreamToString(InputStream is, String charSet) throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is, charSet));
            String lines;
            StringBuffer sb = new StringBuffer();
            while ((lines = reader.readLine()) != null) {
                sb.append(lines);
                sb.append("\r\n");
            }
            return sb.toString();
        } catch (IOException e) {
            throw e;
        } finally {
            if (reader != null) reader.close();
        }
    }
}
